package com.trace.demo.controller;

import com.trace.demo.entity.FarmingActivity;
import com.trace.demo.entity.User;
import com.trace.demo.repository.FarmingActivityRepository;
import com.trace.demo.repository.ProductRepository;
import com.trace.demo.repository.UserRepository;

import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统计数据控制器
 */
@RestController
@RequestMapping("/api/stats")
public class StatsController {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private FarmingActivityRepository activityRepository;

    /**
     * 获取农户统计数据
     */
    @GetMapping("/farmer")
    public ResponseEntity<?> getFarmerStats() {
            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            User currentUser = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户未找到"));

            // 构建统计数据
            Map<String, Object> stats = new HashMap<>();

            // 获取产品总数
            Long productCount = productRepository.countByFarmerId(currentUser.getId());
            stats.put("productCount", productCount);

            // 获取本月新增产品数
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
            Long monthlyNewProducts = productRepository.countByFarmerIdAndCreatedAtAfter(currentUser.getId(), startOfMonth);
            stats.put("monthlyNewProducts", monthlyNewProducts);

            // 获取活动总数
            Long activityCount = activityRepository.countByUser(currentUser);
            stats.put("activityCount", activityCount);

            // 返回统计结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);

            return ResponseEntity.ok(response);

    }

    /**
     * 获取最近活动
     */
    @GetMapping("/activities")
    public ResponseEntity<?> getRecentActivities() {

            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            User currentUser = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户未找到"));

            // 获取最近10条活动
            List<FarmingActivity> activities = activityRepository.findTop10ByUserOrderByCreatedAtDesc(currentUser);

            // 构建响应数据
            List<Map<String, Object>> activityList = activities.stream().map(activity -> {
                Map<String, Object> activityData = new HashMap<>();
                activityData.put("id", activity.getId());
                activityData.put("type", activity.getType());
                activityData.put("content", activity.getContent());
                activityData.put("createdAt", activity.getCreatedAt());
                return activityData;
            }).collect(Collectors.toList());

            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", activityList);

            return ResponseEntity.ok(response);

    }

    /**
     * 获取作物分布数据
     */
    @GetMapping("/crop-distribution")
    public ResponseEntity<?> getCropDistribution() {

            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            User currentUser = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户未找到"));

            // 获取农户的所有产品
            List<Map<String, Object>> productsByCategory = productRepository.findCategoryDistributionByFarmerId(currentUser.getId());

            // 如果没有实际的分类统计方法，模拟一些数据
            if (productsByCategory == null || productsByCategory.isEmpty()) {
                productsByCategory = new ArrayList<>();
                productsByCategory.add(createCategoryData("枸杞", 60));
                productsByCategory.add(createCategoryData("中宁枸杞", 30));
                productsByCategory.add(createCategoryData("青海枸杞", 10));
            }

            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", productsByCategory);

            return ResponseEntity.ok(response);

    }

    /**
     * 辅助方法：创建分类数据
     */
    private Map<String, Object> createCategoryData(String name, int value) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", name);
        data.put("value", value);
        return data;
    }

    /**
     * 获取产量趋势数据
     */
    @GetMapping("/yield-trend")
    public ResponseEntity<?> getYieldTrend() {

            // 获取当前登录用户
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String username = auth.getName();
            User currentUser = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户未找到"));

            // 构建月度产量数据 - 生成模拟数据
            Map<String, Object> trendData = new HashMap<>();

            // 月份数据
            List<String> months = Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月");
            trendData.put("months", months);

            // 产量数据 - 模拟数据
            List<Integer> values = Arrays.asList(120, 132, 101, 134, 90, 230, 210, 180, 200, 190, 220, 110);
            trendData.put("values", values);

            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", trendData);

            return ResponseEntity.ok(response);

    }
}
